package cn.mastor.basic.util;

import cn.mastor.pet.domain.Pet;
import cn.mastor.pet.service.impl.PetServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;

public class FreemarkUtil {

    // 获取自定义的模板生成路径
    public static void testHtml(Long id,String path) throws Exception {
        ApplicationContext context = SpringUtil.getContext();
        FreeMarkerConfigurer freeMarkerConfigurer = context.getBean(FreeMarkerConfigurer.class);
        PetServiceImpl petService = context.getBean(PetServiceImpl.class);
//        PetServiceImpl path = context.getBean(PetServiceImpl.class);
        // 1.创建模板技术的核心配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 2.指定模板名称
        Template template = configuration.getTemplate("/testFreemarker.ftl");
        // 3.准备数据
        Pet pet = petService.getDetail(id);
        String resources = pet.getResources();
        String[] split = resources.split(",");
        pet.setResos(split);
        // 4.根据数据+模板在指定位置生成静态页面
        template.process(pet, new FileWriter(new File(path + "\\" + pet.getId() + ".html")));
    }
}
